package io.github.maojian.bianrytree;

import java.util.AbstractQueue;
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @Auther: jian.mao
 * @Date: 2022-06-22 10:26
 * @Description: https://leetcode.cn/problems/find-bottom-left-tree-value/
 */
public class Q513 {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        TreeNode res = root;
        while (!queue.isEmpty()) {
            int size = queue.size();
            // 记录每层的最左边的值
            res = queue.peek();
            while (size-- > 0) {
                TreeNode treeNode = queue.poll();
                if (treeNode.left != null)
                    queue.offer(treeNode.left);
                if (treeNode.right != null)
                    queue.offer(treeNode.right);
            }
        }
        return res.val;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}